package heman.server.controllers;


import java.util.ArrayList;

import heman.server.entities.Player;
import heman.server.entities.PlayerManager;
import heman.server.entities.Table;
import heman.server.entities.TableManager;



import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.server.interfaces.IProcessServerMessage;


import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;


/**
 * GameOverController controller handles Turn messages with complete=true
 * 
 * 
 * 
 * @author Wenlong Liu
 *
 */
public class GameOverController implements IProcessServerMessage {

	public boolean process(Communicator com, Message m) {
		String originator = m.getOriginator();
		
		

        
		NamedNodeMap map=m.contents().getAttributes();

        
        String tableID=map.
        		getNamedItem("table").getNodeValue();
        Table table=TableManager.getInstance().getTable(tableID);
        String game=table.getGame();
		//Increase the rating of the winner
		Player p=PlayerManager.getInstance().getPlayer(originator);
		if (p!=null){
			p.increaseRating(game);
			//Send playerResponse to all online players
	        
	       
	        StringBuilder sb = new StringBuilder(Message.responseHeader(true));
	        //sb.append("")
	        sb.append("<playerResponse>");
	        
	        sb.append(p.toXMLPlayer());
	        sb.append("</playerResponse></response>");
	        
	        Document d = Message.construct(sb.toString());
	        
	        Message r = new Message (d);
	        r.setOriginator(originator);
	        //The player itself needs to know its rating has been updated
	        r.setRecipient(originator);
	        r.setBroadcast();
	        if (!com.distribute(r)) return false;
	        
	        table.gameOver();
	        
	        //We should also send a table response
	   
	        sb = new StringBuilder(Message.responseHeader(true));
	        sb.append("<tableResponse>");
	        
	        sb.append(table.toXML());
	        sb.append("</tableResponse></response>");
	        d = Message.construct(sb.toString());
	        r = new Message (d);
	        r.setOriginator(originator);
	        //The player itself needs to know its rating has been updated
	        r.setRecipient(originator);
	        r.setBroadcast();
			return com.distribute(r);
			
		}
		return false;
	}

}
